package logic

import (
	"context"
	"errors"
	"github.com/zeromicro/go-zero/core/logx"
	"safe-hub/assrpc/assrpc"
	"safe-hub/assrpc/internal/svc"
	"safe-hub/models/cache"
	"safe-hub/models/mysql"
	"safe-hub/pkg"
)

type LonginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLonginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LonginLogic {
	return &LonginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 登录注册一体化
func (l *LonginLogic) Longin(in *assrpc.LonginRequest) (*assrpc.LonginResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User
	mysql.DB.Debug().Where("username = ?", in.Username).Find(&user)
	if user.ID == 0 {
		users := mysql.User{
			Username: in.Username,
			Password: pkg.MD5(in.Password),
		}
		mysql.DB.Debug().Create(&users)
	} else {
		if pkg.MD5(in.Password) != user.Password {
			return nil, errors.New("密码错误")
		}

		sms, _ := cache.Rdb.Get(l.ctx, "sendsms"+in.Username).Result()
		if in.Sendsms != sms {
			return nil, errors.New("短信错误")
		}

		cha, _ := cache.Rdb.Get(l.ctx, "captcha"+in.Username).Result()
		if in.Captcha != cha {
			return nil, errors.New("图形验证码错误")
		}

	}

	return &assrpc.LonginResponse{
		UserId: int64(user.ID),
	}, nil
}
